<template>
	<view class="login-container">
		<!-- 顶部logo -->
		<view class="logo-area">
			<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
		</view>

		<!-- 登录表单 -->
		<view class="form-area">
			<view class="title">欢迎登录</view>
			<!-- 微信登录按钮 -->
			<button class="wx-login-btn" @click="handleWechatLogin" :loading="wxAuthLoading">
				<text>微信一键登录</text>
			</button>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from "vuex";
	import user from "@/api/user.js";
	import request from '@/utils/request.js'
	// 配置常量
	const WECHAT_CONFIG = {
		appid: 'wx6bd80db273bdbad9',
		backendUrl: 'https://d-dazi.bigchun.com/',
		callback: {
			path: '#/pages/login/login', // 改为对象结构
			fullUrl: 'https://d-dazi.bigchun.com/#/pages/login/login' // 添加完整URL
		},
		sessionStorageKey: 'wx_auth_state',
		scope: 'snsapi_userinfo'
	};

	export default {
		data() {
			return {
				wxAuthLoading: false,
				userInfo: null,
				showAgreement: true, // 是否显示协议提示
				zhituiId: null
			};
		},
		computed: mapGetters(["isLogin", "uid"]),
		onShow(options) {
			console.log(options, 'options_onshow');
		},
		onLoad(options) {
			console.log(options, 'options_onload');
			// 优先检查本地是否有token
			if (uni.getStorageSync('token')) {
				this.redirectToHome();
				return;
			}

			// 检查URL中是否有微信回调的code参数
			this.checkWechatCallback();
		},
		methods: {
			...mapActions(["login", "setUserInfo"]),

			/**
			 * 重定向到首页
			 */
			redirectToHome() {
				uni.switchTab({
					url: "/pages/index/index",
				});
			},
			/**
			 * 生成随机state字符串
			 */
			// generateState() {
			// 	return Math.random().toString(36).substring(2, 15) +
			// 		Math.random().toString(36).substring(2, 15);
			// },

			/**
			 * 处理微信登录按钮点击
			 */
			async handleWechatLogin() {
				try {
					this.wxAuthLoading = true;

					// #ifdef H5
					const state = 'STATE';
					sessionStorage.setItem(WECHAT_CONFIG.sessionStorageKey, state);

					// const wxAuthUrl = this.generateWechatAuthUrl(state);
					console.log('微信授权URL:', wxAuthUrl);
					const wxAuthUrl =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WECHAT_CONFIG.appid}&redirect_uri=${encodeURIComponent(`${WECHAT_CONFIG.backendUrl}${WECHAT_CONFIG.callback.path}`)}&response_type=code&scope=${WECHAT_CONFIG.scope}&state=${state}&connect_redirect=1#wechat_redirect`;

					location.replace(wxAuthUrl);
					// #endif

				} catch (error) {
					console.error('微信登录跳转失败:', error);
					this.wxAuthLoading = false;
				}
			},

			/**
			 * 检查微信回调参数
			 */
			checkWechatCallback() {
				// #ifdef H5
				const params = new URLSearchParams(window.location.search);
				console.log(params, 'params');
				const code = params.get('code');
				const state = params.get('state');

				if (code && state) {
					// 验证state防止CSRF攻击
					const savedState = sessionStorage.getItem(WECHAT_CONFIG.sessionStorageKey);
					sessionStorage.removeItem(WECHAT_CONFIG.sessionStorageKey);
					let zhituiId = uni.getStorageSync('zhitui_id');
					console.log('检测到微信回调参数:', {
						code,
						state,
						zhituiId
					});
					this.exchangeWxCode(code, zhituiId);

					// 清除URL中的code参数
					this.cleanUrlParams();
				}
				// #endif
			},

			/**
			 * 清除URL中的参数
			 */
			cleanUrlParams() {
				const cleanUrl = window.location.pathname;
				window.history.replaceState({}, document.title, cleanUrl);
			},

			/**
			 * 用code换取token
			 */
			// 修改exchangeWxCode方法
			async exchangeWxCode(code, zhituiId) {
				try {
					uni.showLoading({
						title: "登录中...",
						mask: true,
					});
					console.log(zhituiId, 'zhituiId');
					const res = await user.userThirdLogin({
						code: code,
						platform: "wechat",
						zhitui_id: zhituiId || 0, //分享id,在别人扫分享出去的图上的二维码的时候拿到的后缀zhitui_id
					});
					// 立即清除URL参数
					this.cleanUrlParams();
					const userData = res.data.data;
					console.log(userData, 'userData');
					const token = userData.userinfo.token
					const userInfo = userData.userinfo
					const thirdInfo = userData.thirdinfo
					console.log(token, 'token');
					console.log(userInfo, 'userInfo');
					uni.setStorageSync('token', token);
					uni.setStorageSync('userInfo', userInfo);
					if (thirdInfo) {
						uni.setStorageSync('thirdInfo', thirdInfo);
					}
					// 更新Vuex状态
					this.$store.commit('LOGIN', {
						token,
						uid: userInfo.id || userInfo.uid
					});
					this.$store.commit('UPDATE_USERINFO', userInfo);


					uni.showToast({
						title: '登录成功',
						icon: 'success',
					});
					// 立即清除URL参数
					this.cleanUrlParams();
					console.log(111);
					uni.switchTab({
						url: "/pages/index/index",
					});


				} catch (error) {
					console.error("微信登录失败", error);
					this.handleLoginError(error);
					// 即使失败也清除URL参数
					this.cleanUrlParams();
				} finally {
					this.wxAuthLoading = false;
					uni.hideLoading();
				}
			},



			/**
			 * 处理登录成功
			 */
			async handleLoginSuccess(token, userInfo, thirdInfo) {
				try {
					// 保存token和用户信息
					uni.setStorageSync('token', token);
					uni.setStorageSync('userInfo', userInfo);

					if (thirdInfo) {
						uni.setStorageSync('thirdInfo', thirdInfo);
					}

					// 更新Vuex状态
					this.$store.commit('LOGIN', {
						token,
						uid: userInfo.id || userInfo.uid
					});
					this.$store.commit('UPDATE_USERINFO', userInfo);



					// 显示成功提示
					uni.showToast({
						title: '登录成功',
						icon: 'success',
						duration: 1500,
						complete: () => {
							setTimeout(() => {
								this.redirectAfterLogin();
							}, 1500);
						}
					});
				} catch (e) {
					console.error('登录信息处理失败:', e);
					uni.showToast({
						title: '登录成功，但获取用户信息失败',
						icon: 'none'
					});
					this.redirectAfterLogin();
				}
			},

			/**
			 * 登录后跳转处理
			 */
			redirectAfterLogin() {
				// 检查是否有重定向路径
				const redirectUrl = uni.getStorageSync('login_redirect');

				if (redirectUrl) {
					uni.redirectTo({
						url: decodeURIComponent(redirectUrl)
					});
					uni.removeStorageSync('login_redirect');
				} else {
					this.redirectToHome();
				}
			},

			/**
			 * 处理登录错误
			 */
			handleLoginError(error) {
				let message = '登录失败';

				if (error.response?.status === 401) {
					message = '授权已过期，请重新登录';
				} else if (error.message) {
					message = error.message;
				}

				// 特殊处理微信授权错误
				if (message.includes('scope授权错误') || message.includes('invalid code')) {
					message = '微信授权失败，请重试';
				}

				uni.showToast({
					title: message,
					icon: 'none',
					duration: 3000
				});

				// 如果是授权错误，则跳转到登录页面
				if (message.includes('授权')) {
					setTimeout(() => {
						uni.redirectTo({
							url: '/pages/login/login'
						});
					}, 1500);
				}
			}
		},

		onShow() {
			// 每次页面显示时检查是否已登录
			if (uni.getStorageSync('token')) {
				this.redirectToHome();
			}
		}
	};
</script>

<style lang="scss" scoped>
	.login-container {
		padding: 0 60rpx;
		box-sizing: border-box;
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #fff;

		.logo-area {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;

			.logo {
				width: 200rpx;
				height: 200rpx;
				border-radius: 20rpx;
			}
		}

		.form-area {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: flex-end;
			padding-bottom: 100rpx;

			.title {
				font-size: 48rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 80rpx;
				text-align: center;
			}

			.wx-login-btn {
				width: 100%;
				height: 90rpx;
				line-height: 90rpx;
				border-radius: 45rpx;
				background-color: #07C160;
				color: #fff;
				font-size: 32rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 40rpx;

				.wx-icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 15rpx;
				}

				&:after {
					border: none;
				}
			}

			.agreement {
				margin-top: 40rpx;
				font-size: 24rpx;
				color: #999;
				text-align: center;

				.link {
					color: #07C160;
				}
			}
		}
	}
</style>